package cn.wolfcode.crm.service.imp;

import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.mapper.PermissionMapper;
import cn.wolfcode.crm.qo.PageResult;
import cn.wolfcode.crm.qo.QueryObject;
import cn.wolfcode.crm.service.IPermissionService;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.Collection;
import java.util.List;
import java.util.Map;

@Service
public class PermissionServiceImpl implements IPermissionService {
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
   private RequestMappingHandlerMapping rm;
    @Override
    public void deleteByPrimaryKey(Long[] id) {
        if (id != null) {

        permissionMapper.deleteByPrimaryKey(id);
        }
    }


    @Override
    public List<Permission> selectAll() {
        List<Permission> depts = permissionMapper.selectAll();
        return depts;
    }



    @Override
    public PageResult queryForList(QueryObject qo) {
        int rows = permissionMapper.rows(qo);
        if (rows==0) {
            return PageResult.EMPTY_RESULT;
        }
        PageResult result = new PageResult(rows, permissionMapper.queryForList(qo));
        return result;
    }

    //通过员工id查询权限
    public List<String> selectByEmployeeId(Long id) {
        List<String> permissions = permissionMapper.selectByEmployeeId(id);
        return permissions;
    }

    @Override
    //加载权限
    public void reload() {
        //拿到所有requseMapping的方法
        Map<RequestMappingInfo, HandlerMethod> hm = rm.getHandlerMethods();
        Collection<HandlerMethod> ms = hm.values();

        List<String> exps = permissionMapper.selectAllExps();

            for (HandlerMethod m : ms) {

                RequiresPermissions anno = m.getMethod().getAnnotation(RequiresPermissions.class);
                if (anno != null) {
                    //说明此资源需要权限 与数据库判断 是否存在 存入数据库
                    String[] a = anno.value();
                    String exp = a[0];
                    String name = a[1];
                    if (!exps.contains(exp)) {
                        Permission p = new Permission();
                        p.setName(name);
                        p.setExpression(exp);
                        permissionMapper.insert(p);
                }

            }


    }
    }
}
